﻿using PLCS.App.Shared.ViewModels;
using PLCS.Application.Contracts.EquipmentApp.Dtos;
using PLCS.Application.Contracts.LogShowApp.Dtos;
using PLCS.Application.Contracts.PLCConfigApp.Dtos;
using PLCS.Client.IService.ConfigManager;
using PLCS.Client.IService.LogManager;
using PLCS.Shared.Common.Constant;

using Prism.Services.Dialogs;

using System;

using Volo.Abp.ObjectMapping;

namespace PLCS.App.ConfigManager.ViewModels.PLCConfig;

public class PLCConfigDetailViewModel : HostDialogViewModel
{
    private readonly IObjectMapper<ConfigManagerModule> _objectMapper;
    private readonly IPLCConfigService _pLCConfigService;
    private readonly IOperationLogService _logShowService;
    private PLCConfigDto _model;

    public PLCConfigDto Model
    {
        get { return _model; }
        set { _model = value; }
    }

    public PLCConfigDetailViewModel(IObjectMapper<ConfigManagerModule> objectMapper, IPLCConfigService pLCConfigService, IOperationLogService logShowService)
    {
        _objectMapper = objectMapper;
        _pLCConfigService = pLCConfigService;
        this._logShowService = logShowService;
        View = "PLC配置编辑弹窗";
    }

    public override void OnDialogOpened(IDialogParameters parameters)
    {
        if (parameters.ContainsKey("Value"))
        {
            Model = parameters.GetValue<PLCConfigDto>("Value");
            Title = "编辑";
        }
        else
        {
            Title = "新增";
            Model = new PLCConfigDto();
        }
    }

    protected override async void Save()
    {
        try
        {
            SavebuttonIsEnabled = false;
            var plcConfig = _objectMapper.Map<PLCConfigDto, PLCConfigEditDto>(Model);
            if (plcConfig.Id != Guid.Empty)
            {
                await _pLCConfigService.UpdateAsync(plcConfig);
                Log("修改", plcConfig);
            }
            else
            {
                await _pLCConfigService.CreateAsync(plcConfig);
                Log("新增", plcConfig);
            }
            ShowMessage("操作成功");
            base.Save();
        }
        catch (Exception ex)
        {
            ShowMessage(ex.Message);
        }
        finally { SavebuttonIsEnabled = true; }
    }
}